home *** CD-ROM | disk | FTP | other *** search
/ Creative Computers / Creative Computers CD-ROM, Volume 1 (Legendary Design Technologies, Inc.)(1994).iso / text / misc / faq_c_long.txt.pp / faq_c_long.txt
Text File  |  1994-11-17  |  80KB  |  1,911 lines

  1.    Path: amara!sharkey!caen!zaphod.mps.ohio-state.edu!think.com!snorkelwacker.mit.edu!bloom-beacon!adam!scs
  2.    From: scs@adam.mit.edu (Steve Summit)
  3.    Newsgroups: comp.lang.c
  4.    Subject: Answers to Frequently Asked Questions (FAQ) on comp.lang.c
  5.    Message-ID: <1990Dec1.051102.9385@athena.mit.edu>
  6.    Date: 1 Dec 90 05:11:02 GMT
  7.    Expires: 1 Jan 91 05:00:00 GMT
  8.    Sender: daemon@athena.mit.edu (Mr Background)
  9.    Reply-To: scs@adam.mit.edu (Steve Summit)
  10.    Organization: Thermal Technologies, Inc.
  11.    Lines: 1897
  12.    Supersedes: <1990Nov1.050635.14431@athena.mit.edu>
  13.  
  14. [Last modified 11/30/90 by scs.]
  15.  
  16. Certain topics come up again and again on this newsgroup.  They are good
  17. questions, and the answers may not be immediately obvious, but each time
  18. they recur, much net bandwidth and reader time is wasted on repetitive
  19. responses, and on tedious corrections to the incorrect answers which are
  20. inevitably posted.
  21.  
  22. This article, which is posted monthly, attempts to answer these common
  23. questions definitively and succinctly, so that net discussion can move
  24. on to more constructive topics without continual regression to first
  25. principles.
  26.  
  27. This article does not, and cannot, provide an exhaustive discussion of
  28. every subtle point and counterargument which could be mentioned with
  29. respect to these topics.  Cross-references to standard C publications
  30. have been provided, for further study by the interested and dedicated
  31. reader.  A few of the more perplexing and pervasive topics may be
  32. further explored in some in-depth minitreatises posted in conjunction
  33. with this article.
  34.  
  35. No mere newsgroup article can substitute for thoughtful perusal of a
  36. full-length language reference manual.  Anyone interested enough in C to
  37. be following this newsgroup should also be interested enough to read and
  38. study one or more such manuals, preferably several times.  Some vendors'
  39. compiler manuals are unfortunately inadequate; a few even perpetuate
  40. some of the myths which this article attempts to debunk.  Several
  41. noteworthy books on C are listed in this article's bibliography.
  42.  
  43. If you have a question about C which is not answered in this article,
  44. please try to answer it by checking a few of the referenced books, or by
  45. asking knowledgeable colleagues, before posing your question to the net
  46. at large.  There are many people on the net who are happy to answer
  47. questions, but the volume of repetitive answers posted to one question,
  48. as well as the growing numbers of questions as the net attracts more
  49. readers, can become oppressive.  If you have questions or comments
  50. prompted by this article, please reply by mail rather than following up
  51. -- this article is meant to decrease net traffic, not increase it.
  52.  
  53. This article is always being improved.  Your input is welcomed.  Send
  54. your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or
  55. mit-eddie!adam!scs; this article's From: line may be unusable.
  56.  
  57. The questions answered here are divided into several categories:
  58.  
  59.      1. Null Pointers
  60.      2. Arrays and Pointers
  61.      3. Order of Evaluation
  62.      4. ANSI C
  63.      5. C Preprocessor
  64.      6. Variable-Length Argument Lists
  65.      7. Memory Allocation
  66.      8. Structures
  67.      9. Declarations
  68.      10. Boolean Expressions and Variables
  69.      11. Operating System Dependencies
  70.      12. Stdio
  71.      13. Miscellaneous
  72.  
  73. Herewith, some frequently-asked questions and their answers:
  74.  
  75.  
  76. Section 1. Null Pointers
  77.  
  78. 1.  What is this infamous null pointer, anyway?
  79.  
  80. A:  The language definition states that for each pointer type, there is
  81.     a special value -- the "null pointer" -- which is distinguishable
  82.     from all other pointer values and which is not the address of any
  83.     object.  That is, the address-of operator & will never yield a null
  84.     pointer, nor will a successful call to malloc.  (malloc returns a
  85.     null pointer when it fails, and this is a typical use of null
  86.     pointers: as a "special" pointer value with some other meaning,
  87.     usually "not allocated" or "not pointing anywhere yet.")
  88.  
  89.     A null pointer is conceptually different from an uninitialized
  90.     pointer.  A null pointer is known not to point to any object; an
  91.     uninitialized pointer might point anywhere (that is, at some random
  92.     object, or at a garbage or unallocated address).  See also question
  93.     38.
  94.  
  95.     As mentioned in the definition above, there is a null pointer for
  96.     each pointer type, and the internal values of null pointers for
  97.     different types may be different.  Although programmers need not
  98.     know the internal values, the compiler must always be informed which
  99.     type of null pointer is required, so it can make the distinction if
  100.     necessary (see below).
  101.  
  102.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  103.     Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.
  104.  
  105. 2.  How do I "get" a null pointer in my programs?
  106.  
  107. A:  According to the language definition, a constant 0 in a pointer
  108.     context is converted into a null pointer at compile time.  That is,
  109.     in an initialization, assignment, or comparison when one side is a
  110.     variable or expression of pointer type, the compiler can tell that a
  111.     constant 0 on the other side requests a null pointer, and generate
  112.     the correctly-typed null pointer value.  Therefore, the following
  113.     fragments are perfectly legal:
  114.  
  115.          char *p = 0;
  116.          if(p != 0)
  117.  
  118.     However, an argument being passed to a function is not necessarily
  119.     recognizable as a pointer context, and the compiler may not be able
  120.     to tell that an unadorned 0 "means" a null pointer.  For instance,
  121.     the Unix system call "execl" takes a variable-length, null-pointer-
  122.     terminated list of character pointer arguments.  To generate a null
  123.     pointer in a function call context, an explicit cast is typically
  124.     required:
  125.  
  126.          execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  127.  
  128.     If the (char *) cast were omitted, the compiler would not know to
  129.     pass a null pointer, and would pass an integer 0 instead.  (Note
  130.     that many Unix manuals get this example wrong.)
  131.  
  132.     When function prototypes are in scope, argument passing becomes an
  133.     "assignment context," and casts may safely be omitted, since the
  134.     prototype tells the compiler that a pointer is required, and of
  135.     which type, enabling it to correctly cast unadorned 0's.  Function
  136.     prototypes cannot provide the types for variable arguments in
  137.     variable-length argument lists, however, so explicit casts are still
  138.     required for those arguments.  It is safest always to cast null
  139.     pointer function arguments, to guard against varargs functions or
  140.     those without prototypes, to allow interim use of non-ANSI
  141.     compilers, and to demonstrate that you know what you are doing.
  142.  
  143.     Summary:
  144.  
  145.          Unadorned 0 okay:        Explicit cast required:
  146.  
  147.          initialization           function call,
  148.                                   no prototype in scope
  149.          assignments
  150.                                   variable argument to
  151.          comparisons              varargs function
  152.  
  153.          function call,
  154.          prototype in scope,
  155.          fixed argument
  156.  
  157.     References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec.
  158.     A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI Sec.
  159.     3.2.2.3 .
  160.  
  161. 3.  But aren't pointers the same as ints?
  162.  
  163. A:  Not since the early days.  Attempting to turn pointers into
  164.     integers, or to build pointers out of integers, has always been
  165.     machine-dependent and unportable, and doing so is strongly
  166.     discouraged.  (Any object pointer may be cast to the "universal"
  167.     pointer type void *, or char * under a pre-ANSI compiler, when
  168.     heterogeneous pointers must be passed around.)
  169.  
  170.     References: K&R I Sec. 5.6 pp. 102-3; ANSI Sec. 3.2.2.3 p. 37, Sec.
  171.     3.3.4 pp. 46-7.
  172.  
  173. 4.  What is NULL and how is it #defined?
  174.  
  175. A:  As a stylistic convention, many people prefer not to have unadorned
  176.     0's scattered throughout their programs.  For this reason, the
  177.     preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>),
  178.     with value 0 (or (void *)0, about which more later).  A programmer
  179.     who wishes to make explicit the distinction between 0 the integer
  180.     and 0 the null pointer can then use NULL whenever a null pointer is
  181.     required.  This is a stylistic convention only; the preprocessor
  182.     turns NULL back to 0 which is then recognized by the compiler (in
  183.     pointer contexts) as before.  In particular, a cast may still be
  184.     necessary before NULL (as before 0) in a function call argument.
  185.     (The table under question 2 above applies for NULL as well as 0.)
  186.  
  187.     NULL should _only_ be used for pointers.  It should not be used when
  188.     another kind of 0 is required, even though it might work, because
  189.     doing so sends the wrong stylistic message.  (ANSI allows the
  190.     #definition of NULL to be (void *)0, which will not work in non-
  191.     pointer contexts.)  In particular, do not use NULL when the ASCII
  192.     null character (NUL) is desired.  Provide your own definition
  193.  
  194.          #define NUL '\0'
  195.  
  196.     if you must.
  197.  
  198.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  199.     Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
  200.     Rationale Sec. 4.1.5 p. 74.
  201.  
  202. 5.  How should NULL be #defined on a machine which uses a nonzero bit
  203.     pattern as the internal representation of a null pointer?
  204.  
  205. A:  Programmers should never need to know the internal representation(s)
  206.     of null pointers, because they are normally taken care of by the
  207.     compiler.  If a machine uses a nonzero bit pattern for null
  208.     pointers, it is the compiler's responsibility to generate it when
  209.     the programmer requests, by writing "0" or "NULL," a null pointer.
  210.     Therefore, #defining NULL as 0 on a machine for which internal null
  211.     pointers are nonzero is as valid as on any other, because the
  212.     compiler must (and can) still generate the machine's correct null
  213.     pointers in response to unadorned 0's seen in pointer contexts.
  214.  
  215. 6.  If NULL were defined as follows:
  216.  
  217.          #define NULL (char *)0
  218.  
  219.     wouldn't that make function calls which pass an uncast NULL work?
  220.  
  221. A:  Not in general.  The problem is that there are machines which use
  222.     different internal representations for pointers to different types
  223.     of data.  The suggested #definition would make uncast NULL arguments
  224.     to functions expecting pointers to characters to work correctly, but
  225.     pointer arguments to other types would still be problematical, and
  226.     legal constructions such as
  227.  
  228.          FILE *fp = NULL;
  229.  
  230.     could fail.
  231.  
  232.     Nevertheless, ANSI C allows the alternate
  233.  
  234.          #define NULL (void *)0
  235.  
  236.     definition for NULL.  Besides helping incorrect programs to work
  237.     (but only on machines with all pointers the same, thus questionably
  238.     valid assistance) this definition may catch programs which use NULL
  239.     incorrectly (e.g. when the ASCII  NUL character was really
  240.     intended).
  241.  
  242. 7.  I use the preprocessor macro
  243.  
  244.          #define Nullptr(type) (type *)0
  245.  
  246.     to help me build null pointers of the correct type.
  247.  
  248. A:  This trick, though popular with beginning programmers, does not buy
  249.     much.  It is not needed in assignments and comparisons; see question
  250.     2.  It does not even save keystrokes.  Its use suggests to the
  251.     reader that the author is shaky on the subject of null pointers, and
  252.     requires the reader to check the #definition of the macro, its
  253.     invocations, and _all_ other pointer usages much more carefully.
  254.  
  255. 8.  Is the abbreviated pointer comparison "if(p)" to test for non-null
  256.     pointers valid?  What if the internal representation for null
  257.     pointers is nonzero?
  258.  
  259. A:  When C requires the boolean value of an expression (in the if,
  260.     while, for, and do statements, and with the &&, ||, !, and ?:
  261.     operators), a false value is produced when the expression compares
  262.     equal to zero, and a true value otherwise.  That is, whenever one
  263.     writes
  264.  
  265.          if(expr)
  266.  
  267.     where "expr" is any expression at all, the compiler essentially acts
  268.     as if it had been written as
  269.  
  270.          if(expr != 0)
  271.  
  272.     Substituting the trivial pointer expression "p" for "expr," we have
  273.  
  274.          if(p)      is equivalent to                 if(p != 0)
  275.  
  276.     and this is a comparison context, so the compiler can tell that the
  277.     (implicit) 0 is a null pointer, and use the correct value.  There is
  278.     no trickery involved here; compilers do work this way, and generate
  279.     identical code for both statements.  The internal representation of
  280.     a pointer does _not_ matter.
  281.  
  282.     The boolean negation operator, !, can be described as follows:
  283.  
  284.          !expr      is essentially equivalent to     expr?0:1
  285.  
  286.     It is left as an exercise for the reader to show that
  287.  
  288.          if(!p)     is equivalent to                 if(p == 0)
  289.  
  290.     See also question 56.
  291.  
  292.     References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  293.     Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 .
  294.  
  295. 9.  If "NULL" and "0" are equivalent, which should I use?
  296.  
  297. A:  Many programmers believe that "NULL" should be used in all pointer
  298.     contexts, as a reminder that the value is to be thought of as a
  299.     pointer.  Others feel that the confusion surrounding "NULL" and "0"
  300.     is only compounded by hiding "0" behind a #definition, and prefer to
  301.     use unadorned "0" instead.  There is no one right answer.
  302.     C programmers must understand that "NULL" and "0" are
  303.     interchangeable and that an uncast "0" is perfectly acceptable in
  304.     initialization, assignment, and comparison contexts.  Any usage of
  305.     "NULL" (as opposed to "0") should be considered a gentle reminder
  306.     that a pointer is involved; programmers should not depend on it
  307.     (either for their own understanding or the compiler's) for
  308.     distinguishing pointer 0's from integer 0's.  Again, NULL should not
  309.     be used for other than pointers.
  310.  
  311.     Reference: K&R II Sec. 5.4 p. 102.
  312.  
  313. 10. But wouldn't it be better to use NULL (rather than 0) in case the
  314.     value of NULL changes, perhaps on a machine with nonzero null
  315.     pointers?
  316.  
  317. A:  No.  Although preprocessor macros are often used in place of numbers
  318.     because the numbers might change, this is _not_ the reason that NULL
  319.     is used in place of 0.  The language guarantees that source-code 0's
  320.     (in pointer contexts) generate null pointers.  NULL is used only as
  321.     a stylistic convention.
  322.  
  323. 11. I once used a compiler that wouldn't work unless NULL was used.
  324.  
  325. A:  That compiler was broken.  In general, making decisions about a
  326.     language based on the behavior of one particular compiler is likely
  327.     to be counterproductive.
  328.  
  329. 12. I'm confused.  NULL is guaranteed to be 0, but the null pointer is
  330.     not?
  331.  
  332. A:  A "null pointer" (written in lower case in this article) is a
  333.     language concept whose particular internal value does not matter.
  334.     (On some machines the internal value is all-bits-0; on others it is
  335.     not.)  A "null pointer" is requested in source code with the
  336.     character "0".  "NULL" (always in capital letters) is a preprocessor
  337.     macro, which is always #defined as 0 (or (void *)0).
  338.  
  339.     When the term "null" or "NULL" is casually used, one of several
  340.     things may be meant:
  341.  
  342.     1.   The conceptual null pointer, the abstract language concept
  343.          defined in question 1.  It is implemented with...
  344.  
  345.     2.   The internal (or run-time) representation of a null pointer,
  346.          which may or may not be all-bits-0 and which may be different
  347.          for different pointer types.  The actual values should be of
  348.          concern only to compiler writers.  Authors of C programs never
  349.          see them, since they use...
  350.  
  351.     3.   The source code syntax for null pointers, which is the single
  352.          character "0".  It is often hidden behind...
  353.  
  354.     4.   The NULL macro, which is #defined to be "0" or "(void *)0".
  355.          Finally, as a red herring, we have...
  356.  
  357.     5.   The ASCII null character (NUL), which does have all bits zero,
  358.          but has no relation to the null pointer except in name.
  359.  
  360.     This article always uses the phrase "null pointer" for sense 1, the
  361.     character "0" for sense 3, and the capitalized word "NULL" for
  362.     sense 4.
  363.  
  364. 13. Why is there so much confusion surrounding null pointers?  Why do
  365.     these questions come up so often?
  366.  
  367. A:  C programmers traditionally like to know more than they need to
  368.     about the underlying machine implementation.  The fact that null
  369.     pointers are represented both in source code, and internally to most
  370.     machines, as zero invites unwarranted assumptions.  The use of a
  371.     preprocessor macro (NULL) suggests that the value might change
  372.     later, or on some weird machine.  The construct "if(p == 0)" is
  373.     easily misread as calling for conversion of p to an integral type,
  374.     rather than 0 to a pointer type, before the comparison.  Finally,
  375.     the distinction between the several uses of the term "null" (listed
  376.     above) is often overlooked.
  377.  
  378.     One good way to wade out of the confusion is to imagine that C had a
  379.     keyword (perhaps "nil", like Pascal) with which null pointers were
  380.     requested.  The compiler could either turn "nil" into the correct
  381.     type of null pointer, when it could determine the type from the
  382.     source code (as it does with 0's in reality), or complain when it
  383.     could not.  Now, in fact, in C the keyword for a null pointer is not
  384.     "nil" but "0", which works almost as well, except that an uncast "0"
  385.     in a non-pointer context generates an integer zero instead of an
  386.     error message, and if that uncast 0 was supposed to be a null
  387.     pointer, the code may not work.
  388.  
  389. 14. I'm still confused.  I just can't understand all this null pointer
  390.     stuff.
  391.  
  392. A:  Follow these two simple rules:
  393.  
  394.     1.   When you want to refer to a null pointer in source code, use
  395.          "0" or "NULL".
  396.  
  397.     2.   If the usage of "0" or "NULL" is an argument in a function
  398.          call, cast it to the pointer type expected by the function
  399.          being called.
  400.  
  401.     The rest of the discussion has to do with other people's
  402.     misunderstandings, or with the internal representation of null
  403.     pointers, which you shouldn't need to know.  Understand questions 1,
  404.     2, and 4, and consider 9 and 13, and you'll do fine.
  405.  
  406.  
  407. Section 2. Arrays and Pointers
  408.  
  409. 15. I had the declaration char a[5] in one source file, and in another I
  410.     declared extern char *a.  Why didn't it work?
  411.  
  412. A:  The declaration extern char *a simply does not match the actual
  413.     definition.  The type "pointer-to-type-T" is not the same as
  414.     "array-of-type-T."  Use extern char a[].
  415.  
  416.     References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.
  417.  
  418. 16. But I heard that char a[] was identical to char *a.
  419.  
  420. A:  This identity (that a pointer declaration is interchangeable with an
  421.     array declaration, usually unsized) holds _only_ for formal
  422.     parameters to functions.  This identity is related to the fact that
  423.     arrays "decay" into pointers in expressions.  That is, when an array
  424.     name is mentioned in an expression, it is converted immediately into
  425.     a pointer to the array's first element.  Therefore, an array is
  426.     never passed to a function; rather a pointer to its first element is
  427.     passed instead.  Allowing pointer parameters to be declared as
  428.     arrays is a simply a way of making it look as though the array was
  429.     actually being passed.  Some programmers prefer, as a matter of
  430.     style, to use this syntax to indicate that the pointer parameter is
  431.     expected to point to the start of an array rather than to some
  432.     single value.
  433.  
  434.     Since functions can never receive arrays as parameters, any
  435.     parameter declarations which "look like" arrays, e.g.
  436.  
  437.          f(a)
  438.          char a[];
  439.  
  440.     are treated as if they were pointers, since that is what the
  441.     function will receive if an array is passed:
  442.  
  443.          f(a)
  444.          char *a;
  445.  
  446.     To repeat, however, this conversion holds only within function
  447.     formal parameter declarations, nowhere else.  If this conversion
  448.     bothers you, don't use it; many people have concluded that the
  449.     confusion it causes outweighs the small advantage of having the
  450.     declaration "look like" the call and/or the uses within the
  451.     function.
  452.  
  453.     References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3
  454.     p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96;
  455.     ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3 pp. 33-4.
  456.  
  457. 17. So what is meant by the "equivalence of pointers and arrays" in C?
  458.  
  459. A:  Much of the confusion surrounding pointers in C can be traced to a
  460.     misunderstanding of this statement.  Saying that arrays and pointers
  461.     are "equivalent" does not by any means imply that they are
  462.     interchangeable.  (The fact that, as formal parameters to functions,
  463.     array-style and pointer-style declarations are in fact
  464.     interchangeable does nothing to reduce the confusion.)
  465.  
  466.     "Equivalence" refers to the fact (mentioned above) that arrays decay
  467.     into pointers within expressions, and that pointers and arrays can
  468.     both be dereferenced using array-like subscript notation.  That is,
  469.     if we have
  470.  
  471.          char a[10];
  472.          char *p = a;
  473.          int i;
  474.  
  475.     we can refer to a[i] and p[i].  (That pointers can be subscripted
  476.     like arrays is hardly surprising, since arrays have decayed into
  477.     pointers by the time they are subscripted.)
  478.  
  479.     References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec.
  480.     5.4.1 p. 93; ANSI Sec. 3.3.2.1, Sec. 3.3.6 .
  481.  
  482. 18. My compiler complained when I passed a two-dimensional array to a
  483.     routine expecting a pointer to a pointer.
  484.  
  485. A:  The rule by which arrays decay into pointers is not applied
  486.     recursively.  An array of arrays (i.e. a two-dimensional array in C)
  487.     decays into a pointer to an array, not a pointer to a pointer.
  488.     Pointers to arrays are confusing, and it is best to avoid them.
  489.     (The confusion is heightened by the existence of incorrect
  490.     compilers, including some versions of pcc and pcc-derived lint's,
  491.     which improperly accept assignments of multi-dimensional arrays to
  492.     multi-level pointers.)  If you are passing a two-dimensional array
  493.     to a function:
  494.  
  495.          int array[YSIZE][XSIZE];
  496.          f(array);
  497.  
  498.     the function's declaration should match:
  499.  
  500.          f(int a[][XSIZE]) {...}
  501.     or
  502.          f(int (*ap)[XSIZE]) {...}       /* ap is a pointer to an array */
  503.  
  504.     In the first declaration, the compiler performs the usual implicit
  505.     rewriting of "array of array" to "pointer to array;" in the second
  506.     form the pointer declaration is explicit.  The called function does
  507.     not care how big the array is, but it must know its shape, so the
  508.     "column" dimension XSIZE must be included.  In both cases the number
  509.     of "rows" is irrelevant, and omitted.
  510.  
  511.     If a function is already declared as accepting a pointer to a
  512.     pointer, it is probably incorrect to pass a two-dimensional array
  513.     directly to it.
  514.  
  515. 19. How do I declare a pointer to an array?
  516.  
  517. A:  Usually, you don't want to.  Consider using a pointer to one of the
  518.     array's elements instead.  Arrays of type T decay into pointers to
  519.     type T, which is convenient; subscripting or incrementing the
  520.     resultant pointer accesses the individual members of the array.
  521.     True pointers to arrays, when subscripted or incremented, step over
  522.     entire arrays, and are generally only useful when operating on
  523.     multidimensional arrays, if at all.  (See question 18 above.)  When
  524.     people say "pointer to array" casually, they usually mean "pointer
  525.     to array's first element," which is the more useful type.
  526.  
  527.     If you really need to declare a pointer to an entire array, use
  528.     something like "int (*ap)[N];" where N is the size of the array.  If
  529.     the size of the array is unknown, N can be omitted, but the
  530.     resulting type, "pointer to array of unknown size," is almost
  531.     completely useless.  (See also question 51.)
  532.  
  533. 20. How can I dynamically allocate a multidimensional array?
  534.  
  535. A:  It is usually best to allocate an array of pointers, and then
  536.     initialize each pointer to a dynamically-allocated "row." The
  537.     resulting "ragged" array can save space, although it is not
  538.     necessarily contiguous in memory as a real array would be.
  539.  
  540.          int **array = (int **)malloc(nrows * sizeof(int *));
  541.          for(i = 0; i < nrows; i++)
  542.                  array[i] = (int *)malloc(ncolumns * sizeof(int));
  543.  
  544.     (In "real" code, of course, each return value from malloc would have
  545.     to be checked.)
  546.  
  547.     You can keep the array's contents contiguous, while making later
  548.     reallocation of individual rows difficult, with a bit of explicit
  549.     pointer arithmetic:
  550.  
  551.          int **array = (int **)malloc(nrows * sizeof(int *));
  552.          array[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  553.          for(i = 1; i < nrows; i++)
  554.                  array[i] = array[0] + i * ncolumns;
  555.  
  556.     In either case, the elements of the dynamic array can be accessed
  557.     with normal-looking array subscripts: array[i][j].
  558.  
  559.     If the double indirection implied by the above scheme is for some
  560.     reason unacceptable, you can simulate a two-dimensional array with a
  561.     single, dynamically-allocated one-dimensional array:
  562.  
  563.          int *array = (int *)malloc(nrows * ncolumns * sizeof(int));
  564.  
  565.     However, you must now perform subscript calculations manually,
  566.     accessing the i,jth element with array[i * ncolumns + j].  (A macro
  567.     can hide the explicit calculation, but invoking it then requires
  568.     parentheses and commas which don't look exactly like
  569.     multidimensional array subscripts.)
  570.  
  571.  
  572. Section 3. Order of Evaluation
  573.  
  574. 21. Under my compiler, the code
  575.  
  576.          int i = 7;
  577.          printf("%d\n", i++ * i++);
  578.  
  579.     prints 49.  Regardless of the order of evaluation, shouldn't it
  580.     print 56?
  581.  
  582. A:  Although the postincrement and postdecrement operators ++ and --
  583.     perform the operations after yielding the former value, many people
  584.     misunderstand the implication of "after." It is _not_ guaranteed
  585.     that the operation is performed immediately after giving up the
  586.     previous value and before any other part of the expression is
  587.     evaluated.  It is merely guaranteed that the update will be
  588.     performed sometime before the expression is considered "finished"
  589.     (before the next "sequence point," in ANSI C's terminology).  In the
  590.     example, the compiler chose to multiply the previous value by itself
  591.     and to perform both increments afterwards.
  592.  
  593.     The order of other embedded side effects is similarly undefined.
  594.     For example, the expression i + (i = 2) may or may not have the
  595.     value 4.
  596.  
  597.     The behavior of code which contains such ambiguous or undefined side
  598.     effects has always been undefined.  Don't even try to find out how
  599.     your compiler implements such things (contrary to the ill-advised
  600.     exercises in many C textbooks); as K&R wisely point out, "if you
  601.     don't know _how_ they are done on various machines, the innocence
  602.     may help to protect you."
  603.  
  604.     References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI Sec.
  605.     3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.  (Ignore H&S
  606.     Sec. 7.12 pp. 190-1, which is obsolete.)
  607.  
  608. 22. But what about the &&, ||, and comma operators?
  609.     I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  610.  
  611. A:  There is a special exception for those operators, (as well as ?: );
  612.     each of them does imply a sequence point (i.e. left-to-right
  613.     evaluation is guaranteed).  Any book on C should make this clear.
  614.  
  615.     References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R II
  616.     Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Secs. 3.3.13 p. 52,
  617.     3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55, CT&P Sec. 3.7 pp. 46-7.
  618.  
  619.  
  620. Section 4. ANSI C
  621.  
  622. 23. What is the "ANSI C Standard?"
  623.  
  624. A:  In 1983, the American National Standards Institute commissioned a
  625.     committee, X3J11, to standardize the C language.  After a long,
  626.     arduous process, including several widespread public reviews, the
  627.     committee's work was finally ratified as an American National
  628.     Standard, X3.159-1989, on December 14, 1989, and published in the
  629.     spring of 1990.  For the most part, ANSI C standardizes existing
  630.     practice, with a few additions from C++ (most notably function
  631.     prototypes) and support for multinational character sets (including
  632.     the much-lambasted trigraph sequences).  The ANSI C standard also
  633.     formalizes the C run-time library support routines.
  634.  
  635. 24. How can I get a copy of the ANSI C standard?
  636.  
  637. A:  Copies are available from
  638.  
  639.         American National Standards Institute
  640.         1430 Broadway
  641.         New York, NY  10018
  642.         (212) 642-4900
  643.  
  644.     or
  645.  
  646.         Global Engineering Documents
  647.         2805 McGaw Avenue
  648.         Irvine, CA  92714
  649.         (714) 261-1455
  650.         (800) 854-7179
  651.  
  652.     The cost from ANSI is $50.00, plus $6.00 shipping.  Quantity
  653.     discounts are available.  (Note that ANSI derives revenues to
  654.     support its operations from the sale of printed standards, so
  655.     electronic copies are _not_ available.)
  656.  
  657. 25. Does anyone have a tool for converting old-style C programs to ANSI
  658.     C, or for automatically generating prototypes?
  659.  
  660. A:  There are several such programs, many in the public domain.  Check
  661.     your nearest comp.sources archive.  (See also questions 71 and 72.)
  662.  
  663. 26. My ANSI compiler complains about a mismatch when it sees
  664.  
  665.          extern int func(float);
  666.  
  667.          int func(x)
  668.          float x;
  669.          {...
  670.  
  671. A:  You have mixed the new-style prototype declaration
  672.     "extern int func(float);" with the old-style definition "int func(x)
  673.     float x;".  Old C (and ANSI C, in the absence of prototypes)
  674.     silently promotes floats to doubles when passing them as arguments,
  675.     and makes a corresponding silent change to formal parameter
  676.     declarations, so the old-style definition actually says that func
  677.     takes a double.
  678.  
  679.     The problem can be fixed either by using new-style syntax
  680.     consistently in the definition:
  681.  
  682.          int func(float x) { ... }
  683.  
  684.     or by changing the new-style prototype declaration to match the
  685.     old-style definition:
  686.  
  687.          extern int func(double);
  688.  
  689.     (In this case, it would be clearest to change the old-style
  690.     definition to use double as well).
  691.  
  692.     Reference: ANSI Sec. 3.3.2.2 .
  693.  
  694. 27. Why does the ANSI Standard not guarantee more than six monocase
  695.     characters for external identifier significance?
  696.  
  697. A:  The main problem is older linkers which are neither under the
  698.     control of the ANSI standard nor the C compiler developers on the
  699.     systems which have them.  The limitation is only that identifiers be
  700.     _significant_ in the first six characters, not that they be
  701.     restricted to six characters in length.  This limitation is
  702.     annoying, but certainly not unbearable, and is marked in the
  703.     Standard as "obsolescent," i.e. a future revision will likely relax
  704.     it.
  705.  
  706.     This concession to current, restrictive linkers really had to be
  707.     made, no matter how vehemently some people oppose it.  (The
  708.     Rationale notes that its retention was "most painful.")  If you
  709.     disagree, or have thought of a trick by which a compiler burdened
  710.     with a restrictive linker could present the C programmer with the
  711.     appearance of more significance in external identifiers, read the
  712.     excellently-worded X3.159 Rationale, which discusses several such
  713.     schemes and describes why they can't be mandated.
  714.  
  715.     References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale Sec.
  716.     3.1.2 pp. 19-21.
  717.  
  718.  
  719. Section 5. C Preprocessor
  720.  
  721. 28. How can I write a macro to swap two values?
  722.  
  723. A:  There is no good answer to this question.  If the values are
  724.     integers, a well-known trick using exclusive-OR could perhaps be
  725.     used, but it will not work for floating-point values or pointers
  726.     (and the "obvious" supercompressed implementation for integral types
  727.     a^=b^=a^=b is, strictly speaking, illegal due to multiple side-
  728.     effects; and it will not work if the two values are the same
  729.     variable, and...).  If the macro is intended to be used on values of
  730.     arbitrary type (the usual goal), it cannot use a temporary, since it
  731.     does not know what type of temporary it needs, and standard C does
  732.     not provide a typeof operator.  (GNU C does.)
  733.  
  734.     The best all-around solution is probably to forget about using a
  735.     macro.  If you're worried about the use of an ugly temporary, and
  736.     know that your machine provides an exchange instruction, convince
  737.     your compiler vendor to recognize the standard three-assignment swap
  738.     idiom in the optimization phase.
  739.  
  740. 29. I have some old code that tries to construct identifiers with a
  741.     macro like
  742.  
  743.          #define Paste(a, b) a/**/b
  744.  
  745.     but it doesn't work any more.
  746.  
  747. A:  That comments disappeared entirely and could therefore be used for
  748.     token pasting was an undocumented feature of some early preprocessor
  749.     implementations, notably Reiser's.  ANSI affirms (as did K&R) that
  750.     comments are replaced with white space.  However, since the need for
  751.     pasting tokens was demonstrated and real, ANSI introduced a well-
  752.     defined token-pasting operator, ##, which can be used like this:
  753.  
  754.          #define Paste(a, b) a##b
  755.  
  756.     Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  757.  
  758. 30. I'm getting strange syntax errors inside code which I've #ifdeffed
  759.     out.
  760.  
  761. A:  Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef
  762.     must still consist of "valid preprocessing tokens."  This means that
  763.     there must be no unterminated comments or quotes (note particularly
  764.     that an apostrophe within a contracted word in a comment looks like
  765.     the beginning of a character constant), and no newlines inside
  766.     quotes.  Therefore, natural-language comments should always be
  767.     written between the "official" comment delimiters /* and */.
  768.  
  769.     References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  770.  
  771. 31. What's the best way to write a multi-statement cpp macro?
  772.  
  773. A:  The usual goal is to write a macro that can be invoked as if it were
  774.     a single function-call statement.  This means that the "caller" will
  775.     be supplying the final semicolon, so the macro body should not.  The
  776.     macro body cannot be a simple brace-delineated compound statement,
  777.     because syntax errors would result if it were invoked (apparently as
  778.     a single statement, but with a resultant extra semicolon) as the if
  779.     branch of an if/else statement with an explicit else clause.
  780.  
  781.     The traditional solution is to use
  782.  
  783.          #define Func() do { \
  784.                  /* declarations */ \
  785.                  stmt1; \
  786.                  stmt2; \
  787.                  /* ... */ \
  788.                  } while(0)      /* (no trailing ; ) */
  789.  
  790.     When the "caller" appends a semicolon, this expansion becomes a
  791.     single statement regardless of context.  (An optimizing compiler
  792.     will remove any "dead" tests or branches on the constant condition
  793.     0, although lint may complain.)
  794.  
  795.     If all of the statements in the intended macro are simple
  796.     expressions, with no declarations, another technique is to separate
  797.     them with commas and surround them with parentheses.
  798.  
  799.     Reference: CT&P Sec. 6.3 pp. 82-3.
  800.  
  801. 32. How can I write a cpp macro which takes a variable number of
  802.     arguments?
  803.  
  804. A:  One popular trick is to define the macro with a single argument, and
  805.     call it with a double set of parentheses, which appear to the
  806.     compiler to indicate a single argument:
  807.  
  808.          #define DEBUG(args) {printf("DEBUG: "); printf args;}
  809.  
  810.          if(n != 0) DEBUG(("n is %d\n", n));
  811.  
  812.     The obvious disadvantage to this trick is that the caller must
  813.     always remember to use the extra parentheses.  (It is often best to
  814.     use a bona-fide function, which can take a variable number of
  815.     arguments in a well-defined way, rather than a macro.  See questions
  816.     33 and 34 below.)
  817.  
  818.  
  819. Section 6. Variable-Length Argument Lists
  820.  
  821. 33. How can I write a function that takes a variable number of
  822.     arguments?
  823.  
  824. A:  Use varargs or stdarg.
  825.  
  826.     Here is a function which concatenates an arbitrary number of strings
  827.     into malloc'ed memory, using stdarg:
  828.  
  829.          #include <stddef.h>             /* for NULL, size_t */
  830.          #include <stdarg.h>             /* for va_ stuff */
  831.          #include <string.h>             /* for strcat et al */
  832.          #include <stdlib.h>             /* for malloc */
  833.  
  834.          /* VARARGS1 */
  835.  
  836.          char *vstrcat(char *first, ...)
  837.          {
  838.                  size_t len = 0;
  839.                  char *retbuf;
  840.                  va_list argp;
  841.                  char *p;
  842.  
  843.                  if(first == NULL)
  844.                          return NULL;
  845.  
  846.                  len = strlen(first);
  847.  
  848.                  va_start(argp, first);
  849.  
  850.                  while((p = va_arg(argp, char *)) != NULL)
  851.                          len += strlen(p);
  852.  
  853.                  va_end(argp);
  854.  
  855.                  retbuf = malloc(len + 1);       /* +1 for trailing \0 */
  856.  
  857.                  if(retbuf == NULL)
  858.                          return NULL;            /* error */
  859.  
  860.                  (void)strcpy(retbuf, first);
  861.  
  862.                  va_start(argp, first);
  863.  
  864.                  while((p = va_arg(argp, char *)) != NULL)
  865.                          (void)strcat(retbuf, p);
  866.  
  867.                  va_end(argp);
  868.  
  869.                  return retbuf;
  870.          }
  871.  
  872.     Usage is something like
  873.  
  874.          char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  875.  
  876.     Note the cast on the last argument.  (Also note that the caller must
  877.     free the returned, malloc'ed storage.)
  878.  
  879.     Under a pre-ANSI compiler, rewrite the function definition without a
  880.     prototype ("char *vstrcat(first) char *first; {"), #include
  881.     <stdio.h> rather than <stddef.h>, replace "#include <stdlib.h>" with
  882.     "extern char *malloc();", and use int instead of size_t.  You may
  883.     also have to delete the (void) casts, and use the older varargs
  884.     package instead of stdarg.  See the next question for hints.
  885.  
  886.     (If you know enough about your machine's architecture, it is
  887.     possible to pick arguments off of the stack "by hand," but there is
  888.     little reason to do so, since portable mechanisms exist.  If you
  889.     know how to access arguments "by hand," but have access to neither
  890.     <stdarg.h> nor <varargs.h>, you could as easily implement one of
  891.     them, leaving your code portable.)
  892.  
  893.     References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4
  894.     pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  895.  
  896. 34. How can I write a function that takes a format string and a variable
  897.     number of arguments, like printf, and passes them to printf to do
  898.     most of the work?
  899.  
  900. A:  Use vprintf, vfprintf, or vsprintf.
  901.  
  902.     Here is an "error" routine which prints an error message, preceded
  903.     by the string "error: " and terminated with a newline:
  904.  
  905.          #include <stdio.h>
  906.          #include <stdarg.h>
  907.  
  908.          void
  909.          error(char *fmt, ...)
  910.          {
  911.                  va_list argp;
  912.                  fprintf(stderr, "error: ");
  913.                  va_start(argp, fmt);
  914.                  vfprintf(stderr, fmt, argp);
  915.                  va_end(argp);
  916.                  fprintf(stderr, "\n");
  917.          }
  918.  
  919.     To use varargs, instead of stdarg, change the function header to:
  920.  
  921.          void error(va_alist)
  922.          va_dcl
  923.          {
  924.                  char *fmt;
  925.  
  926.     change the va_start line to
  927.  
  928.          va_start(argp);
  929.  
  930.     and add the line
  931.  
  932.          fmt = va_arg(argp, char *);
  933.  
  934.     between the calls to va_start and vfprintf.  (Note that there is no
  935.     semicolon after va_dcl.)
  936.  
  937.     References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12
  938.     p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  939.  
  940. 35. How can I write a function analogous to scanf?
  941.  
  942. A:  Unfortunately, vscanf and the like are not standard.  You're on your
  943.     own.
  944.  
  945. 36. How can I discover how many arguments a function was actually called
  946.     with?
  947.  
  948. A:  This information is not available to a portable program.  Some
  949.     systems have a nonstandard nargs() function available, but its use
  950.     is questionable, since it typically returns the number of words
  951.     pushed, not the number of arguments.  (Floating point values and
  952.     structures are usually passed as several words.)
  953.  
  954.     Any function which takes a variable number of arguments must be able
  955.     to determine from the arguments themselves how many of them there
  956.     are.  printf-like functions do this by looking for formatting
  957.     specifiers (%d and the like) in the format string (which is why
  958.     these functions fail badly if the format string does not match the
  959.     argument list).  Another common technique (useful when the arguments
  960.     are all of the same type) is to use a sentinel value (often 0, -1,
  961.     or an appropriately-cast null pointer) at the end of the list (see
  962.     the vstrcat and execl examples under questions 33 and 2 above).
  963.  
  964. 37. How can I write a function which takes a variable number of
  965.     arguments and passes them to some other function (which takes a
  966.     variable number of arguments)?
  967.  
  968. A:  In general, you cannot.  You must provide a version of that other
  969.     function which accepts a va_list pointer, as does vfprintf in the
  970.     example above.  If the arguments must be passed directly as actual
  971.     arguments (not indirectly through a va_list pointer) to another
  972.     function which is itself variadic (for which you do not have the
  973.     option of creating an alternate, va_list-accepting version) no
  974.     portable solution is possible.  (The problem can be solved by
  975.     resorting to machine-specific assembly language.)
  976.  
  977.  
  978. Section 7. Memory Allocation
  979.  
  980. 38. Why doesn't this program work?
  981.  
  982.          main()
  983.          {
  984.                  char *answer;
  985.                  printf("Type something:\n");
  986.                  gets(answer);
  987.                  printf("You typed \"%s\"\n", answer);
  988.          }
  989.  
  990. A:  The pointer variable "answer," which is handed to the gets function
  991.     as the location into which the response should be stored, has not
  992.     been set to point to any valid storage.  It is an uninitialized
  993.     variable, just as is the variable i in this example:
  994.  
  995.          main()
  996.          {
  997.                  int i;
  998.                  printf("i = %d\n", i);
  999.          }
  1000.  
  1001.     That is, we cannot say where the pointer "answer" points.  (Since
  1002.     local variables are not initialized, and typically contain garbage,
  1003.     it is not even guaranteed that "answer" starts out as a null
  1004.     pointer.)
  1005.  
  1006.     The simplest way to correct the question-asking program is to use a
  1007.     local array, instead of a pointer, and let the compiler worry about
  1008.     allocation:
  1009.  
  1010.          #include <stdio.h>
  1011.          main()
  1012.          {
  1013.                  char answer[100];
  1014.                  printf("Type something:\n");
  1015.                  fgets(answer, 100, stdin);
  1016.                  printf("You typed \"%s\"\n", answer);
  1017.          }
  1018.  
  1019.     Note that this example also uses fgets instead of gets (always a
  1020.     good idea), so that the size of the array can be specified, so that
  1021.     fgets will not overwrite the end of the array if the user types an
  1022.     overly-long line.  (Unfortunately, gets and fgets differ in their
  1023.     treatment of the trailing \n.)  It would also be possible to use
  1024.     malloc to allocate the answer buffer, and/or to parameterize its
  1025.     size (#define ANSWERSIZE 100).
  1026.  
  1027. 39. I can't get strcat to work.  I tried
  1028.  
  1029.          #include <string.h>
  1030.          main()
  1031.          {
  1032.                  char *s1 = "Hello, ";
  1033.                  char *s2 = "world!";
  1034.                  char *s3 = strcat(s1, s2);
  1035.                  printf("%s\n", s3);
  1036.          }
  1037.  
  1038.     but I got strange results.
  1039.  
  1040. A:  Again, the problem is that space for the concatenated result is not
  1041.     properly allocated.  C does not provide a true string type.  C
  1042.     programmers use char *'s for strings, but must always keep
  1043.     allocation in mind.  The compiler will only allocate memory for
  1044.     objects explicitly mentioned in the source code (in the case of
  1045.     "strings," this includes character arrays and string literals).  The
  1046.     programmer must arrange (explicitly) for sufficient space for the
  1047.     results of run-time operations such as string concatenation,
  1048.     typically by declaring arrays, or calling malloc.
  1049.  
  1050.     The simple strcat example could be fixed with something like
  1051.  
  1052.          char s1[20] = "Hello, ";
  1053.          char *s2 = "world!";
  1054.  
  1055.     Note, however, that strcat appends the string pointed to by its
  1056.     second argument to that pointed to by the first, and merely returns
  1057.     its first argument, so the s3 variable is superfluous.
  1058.  
  1059.     Reference: CT&P Sec. 3.2 p. 32.
  1060.  
  1061. Q:  But the man page for strcat said that it took two char *'s as
  1062.     arguments.  How was I supposed to know to allocate things?
  1063.  
  1064. A:  In general, when using pointers you _always_ have to worry about
  1065.     memory allocation, at least to make sure that the compiler is doing
  1066.     it for you.
  1067.  
  1068.     The Synopsis section at the top of a Unix-style man page is often
  1069.     misleading.  The code fragments presented there are closer to the
  1070.     function definition used by the call's implementor than the
  1071.     invocation used by the caller.  In particular, many routines accept
  1072.     pointers (e.g. to strings or structs), yet the caller usually passes
  1073.     the address of some object (an array, or an entire struct).  Another
  1074.     common example is stat().
  1075.  
  1076. 40. You can't use dynamically-allocated memory after you free it, can
  1077.     you?
  1078.  
  1079. A:  No.  Some early man pages for malloc stated that the contents of
  1080.     freed memory was "left undisturbed;" this ill-advised guarantee is
  1081.     not universal and is not required by ANSI.
  1082.  
  1083.     Few programmers would use the contents of freed memory deliberately,
  1084.     but it is easy to do so accidentally.  Consider the following
  1085.     (correct) code for freeing a singly-linked list:
  1086.  
  1087.          struct list *listp, *nextp;
  1088.          for(listp = base; listp != NULL; listp = nextp) {
  1089.                  nextp = listp->next;
  1090.                  free((char *)listp);
  1091.          }
  1092.  
  1093.     and notice what would happen if the more-obvious loop iteration
  1094.     expression listp = listp->next were used, without the temporary
  1095.     nextp pointer.
  1096.  
  1097.     References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  1098.     p. 95.
  1099.  
  1100. 41. What is alloca and why is its use discouraged?
  1101.  
  1102. A:  alloca allocates memory which is automatically freed when the
  1103.     function from which alloca was called returns.  That is, memory
  1104.     allocated with alloca is local to a particular function's "stack
  1105.     frame" or context.
  1106.  
  1107.     alloca cannot be written portably, and is difficult to implement on
  1108.     machines without a stack.  Its use is problematical (and the obvious
  1109.     implementation on a stack-based machine fails) when its return value
  1110.     is passed directly to another function, as in
  1111.     fgets(alloca(100), stdin, 100).
  1112.  
  1113.     For these reasons, alloca cannot be used in programs which must be
  1114.     widely portable, no matter how useful it might be.
  1115.  
  1116.  
  1117. Section 8. Structures
  1118.  
  1119. 42. I heard that structures could be assigned to variables and passed to
  1120.     and from functions, but K&R I says not.
  1121.  
  1122. A:  What K&R I said was that the restrictions on struct operations would
  1123.     be lifted in a forthcoming version of the compiler, and in fact
  1124.     struct assignment and passing were fully functional in Ritchie's
  1125.     compiler even as K&R I was being published.  Although a few early C
  1126.     compilers lacked struct assignment, all modern compilers support it,
  1127.     and it is part of the ANSI C standard, so there should be no
  1128.     reluctance to use it.
  1129.  
  1130.     References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec.
  1131.     5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  1132.  
  1133. 43. How does struct passing and returning work?
  1134.  
  1135. A:  When structures are passed as arguments to functions, the entire
  1136.     struct is typically pushed on the stack, using as many words as are
  1137.     required.  (Pointers to structures are often chosen precisely to
  1138.     avoid this overhead.)
  1139.  
  1140.     Structures are typically returned from functions in a location
  1141.     pointed to by an extra, "hidden" argument to the function.  Older
  1142.     compilers often used a special, static location for structure
  1143.     returns, although this made struct-valued functions nonreentrant,
  1144.     which ANSI C disallows.
  1145.  
  1146.     Reference: ANSI Sec. 2.2.3 p. 13.
  1147.  
  1148. 44. The following program works correctly, but it dumps core after it
  1149.     finishes.  Why?
  1150.  
  1151.          struct list
  1152.                  {
  1153.                  char *item;
  1154.                  struct list *next;
  1155.                  }
  1156.  
  1157.          /* Here is the main program. */
  1158.  
  1159.          main(argc, argv)
  1160.          ...
  1161.  
  1162. A:  A missing semicolon causes the compiler to believe that main returns
  1163.     a struct list.  (The connection is hard to see because of the
  1164.     intervening comment.)  When struct-valued functions are implemented
  1165.     by adding a hidden return pointer, the generated code tries to store
  1166.     a struct with respect to a pointer which was not actually passed (in
  1167.     this case, by the C start-up code).  Attempting to store a structure
  1168.     into memory pointed to by the argc or argv value on the stack (where
  1169.     the compiler expected to find the hidden return pointer) causes the
  1170.     core dump.
  1171.  
  1172.     Reference: CT&P Sec. 2.3 pp. 21-2.
  1173.  
  1174. 45. Why can't you compare structs?
  1175.  
  1176. A:  There is no reasonable way for a compiler to implement struct
  1177.     comparison which is consistent with C's low-level flavor.  A byte-
  1178.     by-byte comparison could be invalidated by random bits present in
  1179.     unused "holes" in the structure (such padding is used to keep the
  1180.     alignment of later fields correct).  A field-by-field comparison
  1181.     would require unacceptable amounts of repetitive, in-line code for
  1182.     large structures.  Either method would not necessarily "do the right
  1183.     thing" with pointer fields: oftentimes, equality should be judged by
  1184.     equality of the things pointed to rather than strict equality of the
  1185.     pointers themselves.
  1186.  
  1187.     If you want to compare two structures, you must write your own
  1188.     function to do so.  C++ (among other languages) would let you
  1189.     arrange for the == operator to map to your function.
  1190.  
  1191.     References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
  1192.     Rationale Sec. 3.3.9 p. 47.
  1193.  
  1194. 46. I came across some code that declared a structure like this:
  1195.  
  1196.          struct name
  1197.                  {
  1198.                  int namelen;
  1199.                  char name[1];
  1200.                  };
  1201.  
  1202.     and then did some tricky allocation to make the name array act like
  1203.     it had several elements.  Is this legal and/or portable?
  1204.  
  1205. A:  This trick is popular, although Dennis Ritchie has called it
  1206.     "unwarranted chumminess with the compiler."  It is surprisingly
  1207.     difficult to determine whether the ANSI C standard allows or
  1208.     disallows it, but it is hard to imagine a compiler or architecture
  1209.     for which it wouldn't work.
  1210.  
  1211. 47. How can I determine the byte offset of a field within a structure?
  1212.  
  1213. A:  ANSI C defines the offsetof macro, which should be used if
  1214.     available.  If you don't have it, a suggested implementation is
  1215.  
  1216.          #define offsetof(type, mem) ((size_t) \
  1217.                  ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  1218.  
  1219.     This implementation is not 100% portable; some compilers may
  1220.     legitimately refuse to accept it.
  1221.  
  1222.     See the next question for a usage hint.
  1223.  
  1224.     Reference: ANSI Sec. 4.1.5 .
  1225.  
  1226. 48. How can I access structure fields by name at run time?
  1227.  
  1228. A:  Build a table of names and offsets, using the offsetof() macro.  The
  1229.     offset of field b in struct a is
  1230.  
  1231.          offsetb = offsetof(struct a, b)
  1232.  
  1233.     If structp is a pointer to an instance of this structure, and b is
  1234.     an int field with offset as computed above, b's value can be set
  1235.     indirectly with
  1236.  
  1237.          *(int *)((char *)structp + offsetb) = value;
  1238.  
  1239.  
  1240. Section 9. Declarations
  1241.  
  1242. 49. I can't seem to define a linked list node which contains a pointer
  1243.     to itself.  I tried
  1244.  
  1245.          typedef struct
  1246.                  {
  1247.                  char *item;
  1248.                  NODEPTR next;
  1249.                  } NODE, *NODEPTR;
  1250.  
  1251.     but the compiler gave me error messages.  Can't a struct in C
  1252.     contain a pointer to itself?
  1253.  
  1254. A:  Structs in C can certainly contain pointers to themselves; the
  1255.     discussion and example in section 6.5 of K&R make this clear.  The
  1256.     problem is that the example above attempts to hide the struct
  1257.     pointer behind a typedef, which is not complete at the time it is
  1258.     used.  First, rewrite it without a typedef:
  1259.  
  1260.          struct node
  1261.                  {
  1262.                  char *item;
  1263.                  struct node *next;
  1264.                  };
  1265.  
  1266.     Then, if you wish to use typedefs, define them after the fact:
  1267.  
  1268.          typedef struct node NODE, *NODEPTR;
  1269.  
  1270.     Alternatively, define the typedefs first (using the line just above)
  1271.     and follow it with the full definition of struct node, which can
  1272.     then use the NODEPTR typedef for the "next" field.
  1273.  
  1274.     References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec.
  1275.     5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  1276.  
  1277. 50. How can I define a pair of mutually referential structures?  I tried
  1278.  
  1279.          typedef struct
  1280.                  {
  1281.                  int structafield;
  1282.                  STRUCTB *bpointer;
  1283.                  } STRUCTA;
  1284.  
  1285.          typedef struct
  1286.                  {
  1287.                  int structbfield;
  1288.                  STRUCTA *apointer;
  1289.                  } STRUCTB;
  1290.  
  1291.     but the compiler doesn't know about STRUCTB when it is used in
  1292.     struct a.
  1293.  
  1294. A:  Again, the problem is not the pointers but the typedefs.  First,
  1295.     define the two structures without using typedefs:
  1296.  
  1297.          struct a
  1298.                  {
  1299.                  int structafield;
  1300.                  struct b *bpointer;
  1301.                  };
  1302.  
  1303.          struct b
  1304.                  {
  1305.                  int structbfield;
  1306.                  struct a *apointer;
  1307.                  };
  1308.  
  1309.     The compiler can accept the field declaration struct b *bpointer
  1310.     within struct a, even though it has not yet heard of struct b.
  1311.     Occasionally it is necessary to precede this couplet with the empty
  1312.     declaration
  1313.  
  1314.          struct b;
  1315.  
  1316.     to mask the declarations (if in an inner scope) from a different
  1317.     struct b in an outer scope.
  1318.  
  1319.     Again, the typedefs could also be defined before, and then used
  1320.     within, the definitions for struct a and struct b.  Problems arise
  1321.     only when an attempt is made to define and use a typedef within the
  1322.     same declaration.
  1323.  
  1324.     References: H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  1325.  
  1326. 51. How do I declare an array of pointers to functions returning
  1327.     pointers to functions returning pointers to characters?
  1328.  
  1329. A:  This question can be answered in at least three ways (all assume the
  1330.     hypothetical array is to have 5 elements):
  1331.  
  1332.     1.   char *(*(*a[5])())();
  1333.  
  1334.     2.   Build it up in stages, using typedefs:
  1335.  
  1336.               typedef char *cp;        /* pointer to char */
  1337.               typedef cp fpc();        /* function returning pointer to char */
  1338.               typedef fpc *pfpc;       /* pointer to above */
  1339.               typedef pfpc fpfpc();    /* function returning... */
  1340.               typedef fpfpc *pfpfpc;   /* pointer to... */
  1341.               pfpfpc a[5];             /* array of... */
  1342.  
  1343.     3.   Use the cdecl program, which turns English into C and vice
  1344.          versa:
  1345.  
  1346.               $ cdecl
  1347.               cdecl> declare a as array 5 of pointer to function returning
  1348.                          pointer to function returning pointer to char
  1349.               char *(*(*a[5])())()
  1350.               cdecl>
  1351.  
  1352.          cdecl can also explain complicated declarations, help with
  1353.          casts, and indicate which set of parentheses the arguments go
  1354.          in (for complicated function definitions).
  1355.  
  1356.     Any good book on C should explain techniques for reading these
  1357.     complicated C declarations "inside out" to understand them
  1358.     ("declaration mimics use").
  1359.  
  1360.     Reference: H&S Sec. 5.10.1 p. 116.
  1361.  
  1362. 52. So where can I get cdecl?
  1363.  
  1364. A:  Several public-domain versions are available.  One is in volume 14
  1365.     of comp.sources.unix .  (Commercial versions may also be available,
  1366.     at least one of which was shamelessly lifted from the public domain
  1367.     copy submitted by Graham Ross, one of cdecl's originators.) See
  1368.     question 72.
  1369.  
  1370.     Reference: K&R II Sec. 5.12 .
  1371.  
  1372. 53. I finally figured out the syntax for declaring pointers to
  1373.     functions, but now how do I initialize one?
  1374.  
  1375. A:  Use something like
  1376.  
  1377.          extern int func();
  1378.          int (*fp)() = func;
  1379.  
  1380.     When the name of a function appears in an expression but is not
  1381.     being called (i.e. is not followed by a "("), it "decays" into a
  1382.     pointer (i.e. its address is implicitly taken), analagously to the
  1383.     implicit decay of an array into a pointer to its first element.
  1384.  
  1385.     An explicit extern declaration for the function is normally needed,
  1386.     since implicit external function declaration does not happen in this
  1387.     case (again, because the function name is not followed by a "(").
  1388.  
  1389. 54. I've seen different methods used for calling through functions to
  1390.     pointers.  Wht's the story?
  1391.  
  1392. A:  Originally, a pointer to a function had to be "turned into" a "real"
  1393.     function, with the * operator (and an extra pair of parentheses, to
  1394.     keep the precedence straight), before calling:
  1395.  
  1396.          int r, f(), (*fp)() = f;
  1397.          r = (*fp)();
  1398.  
  1399.     Another argument says that functions are always called through
  1400.     pointers, but that "real" functions decay implicitly into pointers
  1401.     and so cause no trouble.  This argument, which was adopted by the
  1402.     ANSI standard, means that
  1403.  
  1404.          r = fp();
  1405.  
  1406.     is legal and works correctly (it has always been unambiguous;
  1407.     there's nothing you ever could have done with a function pointer
  1408.     except call through it).  The explicit * is harmless, and still
  1409.     allowed (and recommended, if portability to older compilers is
  1410.     important).
  1411.  
  1412.     References: ANSI Sec. 3.3.2.2 .
  1413.  
  1414.  
  1415. Section 10. Boolean Expressions and Variables
  1416.  
  1417. 55. What is the right type to use for boolean values in C?  Why isn't it
  1418.     a standard type?  Should #defines or enums be used for the true and
  1419.     false values?
  1420.  
  1421. A:  C does not provide a standard boolean type, because picking one
  1422.     involves a space/time tradeoff which is best decided by the
  1423.     programmer.  (Using an int for a boolean may be faster, while using
  1424.     char will probably save data space.)
  1425.  
  1426.     The choice between #defines and enums is arbitrary and not terribly
  1427.     interesting.  Use any of
  1428.  
  1429.          #define TRUE  1             #define YES 1
  1430.          #define FALSE 0             #define NO  0
  1431.  
  1432.          enum bool {false, true};    enum bool {no, yes};
  1433.  
  1434.     or use raw 1 and 0, as long as you are consistent within one program
  1435.     or project.  (The enum may be preferable if your debugger expands
  1436.     enum values when examining variables.)
  1437.  
  1438.     Some people prefer variants like
  1439.  
  1440.          #define TRUE (1==1)
  1441.          #define FALSE (!TRUE)
  1442.  
  1443.     or define "helper" macros such as
  1444.  
  1445.          #define Istrue(e) ((e) != 0)
  1446.  
  1447.     These don't buy anything (see below).
  1448.  
  1449. 56. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is
  1450.     considered "true" in C?  What if a built-in boolean or relational
  1451.     operator "returns" something other than 1?
  1452.  
  1453. A:  It is true (sic) that any nonzero value is considered true in C, but
  1454.     this applies only "on input", i.e. where a boolean value is
  1455.     expected.  When a boolean value is generated by a built-in operator,
  1456.     it is guaranteed to be 1 or 0.  Therefore, the test
  1457.  
  1458.          if((a == b) == TRUE)
  1459.  
  1460.     will work as expected (as long as TRUE is 1), but it is obviously
  1461.     silly.  In general, explicit tests against TRUE and FALSE are
  1462.     undesirable, because some library functions (notably isupper,
  1463.     isalpha, etc.) return, on success, a nonzero value which is _not_
  1464.     necessarily 1.  (Besides, if you believe that "if((a == b) == TRUE)"
  1465.     is an improvement over "if(a == b)", why stop there?  Why not use
  1466.     "if(((a == b) == TRUE) == TRUE)"?)  A good rule of thumb is to use
  1467.     TRUE and FALSE (or the like) only for assignment to a Boolean
  1468.     variable, or as the return value from a Boolean function, never in a
  1469.     comparison.
  1470.  
  1471.     Preprocessor macros like TRUE and FALSE (and, in fact, NULL) are
  1472.     used for code readability, not because the underlying values might
  1473.     ever change.  That "true" is 1 and "false" (and source-code null
  1474.     pointers) 0 is guaranteed by the language.  (See also question 8.)
  1475.  
  1476.     References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7
  1477.     p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13,
  1478.     3.3.14, 3.3.15, 3.6.4.1, 3.6.5 .
  1479.  
  1480. 57. What is the difference between an enum and a series of preprocessor
  1481.     #defines?
  1482.  
  1483. A:  At the present time, there is little difference.  Although many
  1484.     people might have wished otherwise, the ANSI standard says that
  1485.     enums may be freely intermixed with integral types, without errors.
  1486.     (If such intermixing were disallowed without explicit casts,
  1487.     judicious use of enums could catch certain programming errors.)
  1488.  
  1489.     The advantages of enums are that the numeric values are
  1490.     automatically assigned, that a debugger may be able to display the
  1491.     symbolic values when enum variables are examined, and that a
  1492.     compiler may generate nonfatal warnings when enums and ints are
  1493.     indiscriminately mixed (such mixing can still be considered bad
  1494.     style even though it is not strictly illegal).
  1495.  
  1496.     References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5
  1497.     p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  1498.  
  1499.  
  1500. Section 11. Operating System Dependencies
  1501.  
  1502. 58. How can I read a single character from the keyboard without waiting
  1503.     for a newline?
  1504.  
  1505. A:  Contrary to popular belief and many people's wishes, this is not a
  1506.     C-related question.  The delivery of characters from a "keyboard" to
  1507.     a C program is a function of the operating system in use, and cannot
  1508.     be standardized by the C language.  If you are using curses, use its
  1509.     cbreak() function.  Under UNIX, use ioctl to play with the terminal
  1510.     driver modes (CBREAK or RAW under "classic" versions; ICANON,
  1511.     c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems).  Under
  1512.     MS-DOS, use getch().  Under other operating systems, you're on your
  1513.     own.  Beware that some operating systems make this sort of thing
  1514.     impossible, because character collection into input lines is done by
  1515.     peripheral processors not under direct control of the CPU running
  1516.     your program.
  1517.  
  1518.     Operating system specific questions are not appropriate for
  1519.     comp.lang.c .  Many common questions are answered in frequently-
  1520.     asked questions postings in such groups as comp.unix.questions and
  1521.     comp.os.msdos.programmer .  Note that the answers are often not
  1522.     unique even across different versions of Unix.  Bear in mind when
  1523.     answering system-specific questions that the answer that applies to
  1524.     your system may not apply to everyone else's.
  1525.  
  1526.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1.
  1527.  
  1528. 59. How can I find out if there are characters available for reading
  1529.     (and if so, how many)?  Alternatively, how can I do a read that will
  1530.     not block if there are no characters available?
  1531.  
  1532. A:  These, too, are entirely operating-system-specific.  Some versions
  1533.     of curses have a nodelay() function.  Depending on your system, you
  1534.     may also be able to use "nonblocking I/O", or a system call named
  1535.     "select", or the FIONREAD ioctl, or O_NDELAY, or a kbhit() routine.
  1536.  
  1537. 60. How can my program discover the complete pathname to the executable
  1538.     file from which it was invoked?
  1539.  
  1540. A:  Depending on the operating system, argv[0] may contain all or part
  1541.     of the pathname.  (It may also contain nothing.)  You may be able to
  1542.     duplicate the command language interpreter's search path logic to
  1543.     locate the executable if the name in argv[0] is incomplete.
  1544.     However, there is no guaranteed or portable solution.
  1545.  
  1546. 61. How can a process change an environment variable in its caller?
  1547.  
  1548. A:  In general, it cannot.  Different operating systems implement
  1549.     name/value functionality similar to the Unix environment in many
  1550.     different ways.  Whether the "environment" can be usefully altered
  1551.     by a running program, and if so, how, is entirely system-dependent.
  1552.  
  1553.     Under Unix, a process can modify its own environment (some systems
  1554.     provide setenv() or putenv() functions to do this), and the modified
  1555.     environment is passed on to any child processes, but it is _not_
  1556.     propagated back to the parent process.  (The environment of the
  1557.     parent process can only be altered if the parent is explicitly set
  1558.     up to listen for some kind of change requests.  The conventional
  1559.     execution of the BSD "tset" program in .profile and .login files
  1560.     effects such a scheme.)
  1561.  
  1562. 62. How can a file be shortened in-place without completely clearing or
  1563.     rewriting it?
  1564.  
  1565. A:  BSD systems provide ftruncate(), and some MS-DOS compilers supply
  1566.     chsize(), but there is no portable solution.
  1567.  
  1568.  
  1569. Section 12. Stdio
  1570.  
  1571. 63. Why does errno contain ENOTTY after a call to printf?
  1572.  
  1573. A:  Many implementations of the stdio package adjust their behavior
  1574.     slightly if stdout is a terminal.  To make the determination, these
  1575.     implementations perform an operation which fails (with ENOTTY) if
  1576.     stdout is not a terminal.  Although the output operation goes on to
  1577.     complete successfully, errno still contains ENOTTY.  This behavior
  1578.     can be mildly confusing, but it is not strictly incorrect, because
  1579.     it is only meaningful for a program to inspect the contents of errno
  1580.     after an error has occurred (that is, after a library function that
  1581.     sets errno on error has returned an error code).
  1582.  
  1583.     Reference: CT&P Sec. 5.4 p. 73.
  1584.  
  1585. 64. My program's prompts and intermediate output don't always show up on
  1586.     the screen, especially when I pipe the output through another
  1587.     program.
  1588.  
  1589. A:  It is best to use an explicit fflush(stdout) at any point within
  1590.     your program at which output should definitely be visible.  Several
  1591.     mechanisms attempt to perform the fflush for you, at the "right
  1592.     time," but they do not always work, particularly when stdout is a
  1593.     pipe rather than a terminal.
  1594.  
  1595. 65. When I read from the keyboard with scanf(), it seems to hang until I
  1596.     type one extra line of input.
  1597.  
  1598. A:  scanf() was designed for free-format input, which is seldom what you
  1599.     want when reading from the keyboard.  In particular, "\n" in a
  1600.     format string does not mean "expect a newline", it means "discard
  1601.     all whitespace".  But the only way to discard all whitespace is to
  1602.     continue reading the stream until a non-whitespace character is seen
  1603.     (which is then left in the buffer for the next input), so the effect
  1604.     is that it keeps going until it sees a nonblank line.
  1605.  
  1606. 66. So what should I use instead?
  1607.  
  1608. A:  You could use a "%c" format, which will read one character that you
  1609.     can then manually compare against a newline; or "%*c" and no
  1610.     variable if you're willing to trust the user to hit a newline; or
  1611.     "%*[^\n]%*c" to discard everything up to and including the newline.
  1612.     Usually the best solution is to use fgets() to read a whole line,
  1613.     and then use sscanf() or other string functions to parse the line
  1614.     buffer.
  1615.  
  1616.  
  1617. Section 13. Miscellaneous
  1618.  
  1619. 67. Can someone tell me how to write itoa (the inverse of atoi)?
  1620.  
  1621. A:  Just use sprintf.  (You'll have to allocate space for the result
  1622.     somewhere anyway; see questions 38 and 39.  Don't worry that sprintf
  1623.     may be overkill, potentially wasting run time or code space; it
  1624.     works well in practice.)
  1625.  
  1626. 68. I know that the library routine localtime will convert a time_t into
  1627.     a broken-down struct tm, and that ctime will convert a time_t to a
  1628.     printable string.  How can I perform the inverse operations of
  1629.     converting a struct tm or a string into a time_t?
  1630.  
  1631. A:  ANSI C specifies a library routine, mktime, which converts a
  1632.     struct tm to a time_t.  Several public-domain versions of this
  1633.     routine are available in case your compiler does not support it yet.
  1634.  
  1635.     Converting a string to a time_t is harder, because of the wide
  1636.     variety of date and time formats which should be parsed.  Public-
  1637.     domain routines have been written for performing this function, as
  1638.     well, but they are less likely to become standardized.
  1639.  
  1640.     References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI Sec.
  1641.     4.12.2.3 .
  1642.  
  1643. 69. How can I write data files which can be read on other machines with
  1644.     different word size, byte order, or floating point formats?
  1645.  
  1646. A:  The best solution is to use a text file (usually ASCII), written
  1647.     with fprintf and read with fscanf or the like.  Be very skeptical of
  1648.     arguments that text files are too big, or that reading and writing
  1649.     them is too slow.  Not only is their efficiency frequently adequate
  1650.     in practice, but the advantages of being able to manipulate them
  1651.     with standard tools can be overwhelming.
  1652.  
  1653.     If you must use a binary format, you can improve portability, and
  1654.     perhaps take advantage of prewritten I/O libraries, by making use of
  1655.     standardized formats such as Sun's XDR or OSI's ASN.1 .
  1656.  
  1657. 70. I seem to be missing the system header file <sgtty.h>.  Can someone
  1658.     send me a copy?
  1659.  
  1660. A:  Standard headers exist in part so that definitions appropriate to
  1661.     your compiler, operating system, and processor can be supplied.  You
  1662.     cannot just pick up a copy of someone else's header file and expect
  1663.     it to work, unless that person uses exactly the same environment.
  1664.     Ask your compiler vendor why the file was not provided (or to send a
  1665.     replacement copy).
  1666.  
  1667. 71. Does anyone know of a program for converting Pascal (Fortran, lisp,
  1668.     "Old" C, ...) to C?
  1669.  
  1670. A:  Several public-domain programs are available:
  1671.  
  1672.     p2c             written by Dave Gillespie, and posted to
  1673.                     comp.sources.unix in March, 1990 (Volume 21).
  1674.  
  1675.     ptoc            another comp.sources.unix contribution, this one
  1676.                     written in Pascal (comp.sources.unix, Volume 10,
  1677.                     also patches in Volume 13?).
  1678.  
  1679.     f2c             jointly developed by people from Bell Labs,
  1680.                     Bellcore, and Carnegie Mellon.  To find about f2c,
  1681.                     send the message "send index from f2c" to
  1682.                     netlib@research.att.com or research!netlib.
  1683.  
  1684.     FOR_C           Available from:
  1685.  
  1686.                          Cobalt Blue
  1687.                          2940 Union Ave., Suite C
  1688.                          San Jose, CA  95124
  1689.                          (408) 723-0474
  1690.  
  1691.     Promula.Fortran Available from
  1692.  
  1693.                          Promula Development Corp.
  1694.                          3620 N. High St., Suite 301
  1695.                          Columbus, OH 43214
  1696.                          (614) 263-5454
  1697.  
  1698.     The comp.sources.unix archives also contain converters between
  1699.     "K&R" C and ANSI C.
  1700.  
  1701. 72. Where can I get copies of all these public-domain programs?
  1702.  
  1703. A:  If you have access to Usenet, see the regular postings in the
  1704.     comp.sources.unix and comp.sources.misc newsgroups, which describe,
  1705.     in some detail, the archiving policies and how to retrieve copies.
  1706.     The usual approach is to use anonymous ftp and/or uucp from a
  1707.     central, public-spirited site, such as uunet.uu.net.  However, this
  1708.     article cannot track or list all of the available sites and how to
  1709.     access them.
  1710.  
  1711. 73. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C?
  1712.     (And vice versa?)
  1713.  
  1714. A:  The answer is entirely dependent on the machine and the specific
  1715.     calling sequences of the various compilers in use, and may not be
  1716.     possible at all.  Read your compiler documentation very carefully;
  1717.     sometimes there is a "mixed-language programming guide," although
  1718.     the techniques for passing arguments and ensuring correct run-time
  1719.     startup are often arcane.
  1720.  
  1721. 74. Why don't C comments nest?  Are they legal inside quoted strings?
  1722.  
  1723. A:  Nested comments would cause more harm than good, mostly because of
  1724.     the possibility of accidentally leaving comments unclosed by
  1725.     including the characters "/*" within them.  For this reason, it is
  1726.     usually better to "comment out" large sections of code, which might
  1727.     contain comments, with #ifdef or #if 0.
  1728.  
  1729.     The character sequences /* and */ are not special within double-
  1730.     quoted strings, and do not therefore introduce comments, because a
  1731.     program (particularly one which is generating C code as output)
  1732.     might want to print them.  It is hard to imagine why anyone would
  1733.     want or need to place a comment inside a quoted string.  It is easy
  1734.     to imagine a program needing to print "/*".
  1735.  
  1736.     Reference: ANSI Rationale Sec. 3.1.9 p. 33.
  1737.  
  1738. 75. My floating-point calculations are acting strangely and giving me
  1739.     different answers on different machines.
  1740.  
  1741. A:  Most digital computers use floating-point formats which provide a
  1742.     close but by no means exact simulation of real number arithmetic.
  1743.     Among other things, the associative and distributive laws do not
  1744.     hold exactly (that is, order of calculation may be important, and
  1745.     repeated addition is not necessarily equivalent to multiplication).
  1746.  
  1747.     Don't assume that floating-point results will be exact, and
  1748.     especially don't assume that floating-point values can be compared
  1749.     for equality.  (Don't stick random "fuzz factors" in, either.)
  1750.  
  1751.     These problems are no worse for C than they are for any other
  1752.     language.  Languages usually define floating-point semantics as
  1753.     "however the processor does them;" otherwise a compiler for a
  1754.     machine without the "right" model would have to do prohibitively
  1755.     expensive emulations.
  1756.  
  1757.     This article cannot begin to list the pitfalls associated with, and
  1758.     workarounds appropriate for, floating-point work.  A good
  1759.     programming text should cover the basics.  (Beware that subtle
  1760.     problems can occupy numerical analysts for years.)
  1761.  
  1762.     References: K&P Sec. 6 pp. 115-8.
  1763.  
  1764. 76. I'm having trouble with a Turbo C program which crashes and says
  1765.     something like "floating point not loaded."
  1766.  
  1767. A:  Some compilers for small machines, including Turbo C (and Ritchie's
  1768.     original PDP-11 compiler), leave out floating point support if it
  1769.     looks like it will not be needed.  In particular, the non-floating-
  1770.     point versions of printf and scanf save space by not including code
  1771.     to handle %e, %f, and %g.  It happens that Turbo C's heuristics for
  1772.     determining whether the program uses floating point are occasionally
  1773.     insufficient, and the programmer must insert one dummy explicit
  1774.     floating-point operation to force loading of floating-point support.
  1775.     Unfortunately, an apparently common sort of program (thus the
  1776.     frequency of the question) uses scanf to read, and/or printf to
  1777.     print, floating-point values upon which no arithmetic is done.
  1778.  
  1779.     In general, questions about a particular compiler are inappropriate
  1780.     for comp.lang.c .  Problems with PC compilers, for instance, will
  1781.     find a more receptive audience in a PC newsgroup.
  1782.  
  1783. 77. Does anyone have a C compiler test suite I can use?
  1784.  
  1785. A:  Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA), among others,
  1786.     sells one.
  1787.  
  1788. 78. Where can I get a YACC grammar for C?
  1789.  
  1790. A:  The definitive grammar is of course the one in the ANSI standard.
  1791.     Several copies are floating around; keep your eyes open.  There is
  1792.     one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z .
  1793.     FSF's GNU C compiler contains a grammar, as does the appendix to
  1794.     K&R II.
  1795.  
  1796.     Reference: ANSI Sec. A.2 .
  1797.  
  1798. 79. What's the best style for code layout in C?
  1799.  
  1800. A:  K&R, while providing the example most often copied, also supply a
  1801.     good excuse for avoiding it:
  1802.  
  1803.           The position of braces is less important; we have
  1804.           chosen one of several popular styles.  Pick a style
  1805.           that suits you, then use it consistently.
  1806.  
  1807.      It is more important that the layout chosen be consistent (with
  1808.      itself, and with nearby or common code) than that it be "perfect."
  1809.      If your coding environment (i.e. co-workers or company policy) does
  1810.      not suggest a style, and you don't feel like inventing your own,
  1811.      just copy K&R.  (The tradeoffs between various indenting and brace
  1812.      placement options can be exhaustively and minutely examined, but
  1813.      don't warrant repetition here.)
  1814.  
  1815.      Reference: K&R I Sec. 1.2 p. 10.
  1816.  
  1817. 80. Where can I get the "Indian Hill Style Guide" and other coding
  1818.     standards?
  1819.  
  1820. A:  Various standards are available for anonymous ftp from:
  1821.  
  1822.          Site:                     File or directory:
  1823.  
  1824.          cs.washington.edu         ~ftp/pub/cstyle.tar.Z
  1825.          (128.95.1.4)              (the updated Indian Hill guide)
  1826.  
  1827.          cs.toronto.edu            doc/programming
  1828.  
  1829.          giza.cis.ohio-state.edu   pub/style-guide
  1830.  
  1831.          prep.ai.mit.edu           pub/gnu/standards.text
  1832.  
  1833. 81. How do you pronounce "char"?  What's that funny name for the "#"
  1834.     character?
  1835.  
  1836. A:  You can make "char" rhyme with "far" or "bear;" the choice is
  1837.     arbitrary.  Bell Labs once proposed the (now obsolete) term
  1838.     "octothorpe" for the "#" character.
  1839.  
  1840.     Trivia questions like these aren't any more pertinent for
  1841.     comp.lang.c than they are for any of the other groups they
  1842.     frequently come up in.  The "jargon file" (also published as _The
  1843.     Hacker's Dictionary_), contains lots of tidbits like these, as does
  1844.     the official Usenet ASCII pronunciation list, maintained by Maarten
  1845.     Litmaath.  (The pronunciation list also appears in the jargon file
  1846.     under ASCII, as well as in the comp.unix frequently-asked questions
  1847.     list.)
  1848.  
  1849. 82. Where can I get extra copies of this list?  What about back issues?
  1850.  
  1851. A:  For now, just pull it off the net; it is normally posted on the
  1852.     first of each month, with an Expiration: line which should keep it
  1853.     around all month.  Eventually, it may be available for anonymous
  1854.     ftp, or via a mailserver.  (Note that the size of the list is
  1855.     monotonically increasing; older copies are obsolete and don't
  1856.     contain much, except the occasional typo, that the current list
  1857.     doesn't.)
  1858.  
  1859.  
  1860. Bibliography
  1861.  
  1862. ANSI    American National Standard for Information Systems --
  1863.         Programming Language -- C, ANSI X3.159-1989.
  1864.  
  1865. H&S     Samuel P. Harbison and Guy L. Steele, C: A Reference Manual,
  1866.         Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0.  (A
  1867.         third edition has recently been released.)
  1868.  
  1869. PCS     Mark R. Horton, Portable C Software, Prentice Hall, 1990, ISBN
  1870.         0-13-868050-7.
  1871.  
  1872. K&P     Brian W. Kernighan and P.J. Plaugher, The Elements of
  1873.         Programming Style, Second Edition, McGraw-Hill, 1978, ISBN 0-
  1874.         07-034207-5.
  1875.  
  1876. K&R I   Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  1877.         Language, Prentice Hall, 1978, ISBN 0-13-110163-3.
  1878.  
  1879. K&R II  Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  1880.         Language, Second Edition, Prentice Hall, 1988, ISBN 0-13-
  1881.         110362-8, 0-13-110370-9.
  1882.  
  1883. CT&P    Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989, ISBN
  1884.         0-201-17928-8.
  1885.  
  1886. There is a more extensive bibliography in the revised Indian Hill style
  1887. guide; see question 80.
  1888.  
  1889.  
  1890. Acknowledgements
  1891.  
  1892. Thanks to Mark Brader, Joe Buehler, Raymond Chen, Christopher Calabrese,
  1893. Norm Diamond, Ray Dunn, Stephen M. Dunn, Bjorn Engsig, Doug Gwyn, Tony
  1894. Hansen, Joe Harrington, Guy Harris, Karl Heuer, Blair Houghton, Kirk
  1895. Johnson, Andrew Koenig, John Lauro, Christopher Lott, Evan Manning, Mark
  1896. Moraes, Francois Pinard, randall@virginia, Rich Salz, Paul Sand,
  1897. Patricia Shanahan, Joshua Simons, Henry Spencer, Erik Talvola, Clarke
  1898. Thatcher, Chris Torek, and Freek Wiedijk, who have contributed, directly
  1899. or indirectly, to this article.
  1900.  
  1901.                                              Steve Summit
  1902.                                              scs@adam.mit.edu
  1903.                                              scs%adam.mit.edu@mit.edu
  1904.                                              mit-eddie!adam!scs
  1905.  
  1906. This article is Copyright 1988, 1990 by Steve Summit.
  1907. It may be freely redistributed so long as the author's name, and this
  1908. notice, are retained.
  1909. The C code in this article (vstrcat, error, etc.) is public domain and
  1910. may be used without restriction.
  1911.